package repository

import (
	"errors"

	"gorm.io/gorm"

	"pool/pool_backend/internal/models"
	"pool/pool_backend/pkg/logger"
)

// UserRepository 用户仓库接口
type UserRepository interface {
	// CreateUser 创建用户
	CreateUser(user *models.User) error
	// GetUserByAddress 根据地址获取用户
	GetUserByAddress(address string) (*models.User, error)
	// UpdateUser 更新用户
	UpdateUser(user *models.User) error
	// GetSubUsers 获取下级用户
	GetSubUsers(address string) ([]*models.SubUser, error)
	// GetUserCount 获取用户总数
	GetUserCount() (int64, error)
	// GetInviteeCount 获取邀请用户数
	GetInviteeCount(address string) (int64, error)
}

// userRepositoryImpl 用户仓库实现
type userRepositoryImpl struct {
	db *gorm.DB
}

// NewUserRepository 创建用户仓库
func NewUserRepository(db *gorm.DB) UserRepository {
	return &userRepositoryImpl{db: db}
}

// CreateUser 创建用户
func (r *userRepositoryImpl) CreateUser(user *models.User) error {
	result := r.db.Create(user)
	if result.Error != nil {
		logger.ErrorF("Failed to create user: %v", result.Error)
		return result.Error
	}
	return nil
}

// GetUserByAddress 根据地址获取用户
func (r *userRepositoryImpl) GetUserByAddress(address string) (*models.User, error) {
	var user models.User
	result := r.db.Where("address = ?", address).First(&user)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // 返回nil表示用户不存在
		}
		logger.ErrorF("Failed to get user by address: %v", result.Error)
		return nil, result.Error
	}
	return &user, nil
}

// UpdateUser 更新用户
func (r *userRepositoryImpl) UpdateUser(user *models.User) error {
	result := r.db.Save(user)
	if result.Error != nil {
		logger.ErrorF("Failed to update user: %v", result.Error)
		return result.Error
	}
	return nil
}

// GetSubUsers 获取下级用户
func (r *userRepositoryImpl) GetSubUsers(address string) ([]*models.SubUser, error) {
	var users []models.User
	result := r.db.Where("parent_id = ?", address).Find(&users)
	if result.Error != nil {
		logger.ErrorF("Failed to get sub users: %v", result.Error)
		return nil, result.Error
	}

	// 转换为SubUser
	subUsers := make([]*models.SubUser, len(users))
	for i, user := range users {
		subUsers[i] = &models.SubUser{
			Address:     user.Address,
			Token:       user.Token,
			LastCheckIn: user.LastCheckIn,
		}
	}

	return subUsers, nil
}

// GetUserCount 获取用户总数
func (r *userRepositoryImpl) GetUserCount() (int64, error) {
	var count int64
	result := r.db.Model(&models.User{}).Count(&count)
	if result.Error != nil {
		logger.ErrorF("Failed to get user count: %v", result.Error)
		return 0, result.Error
	}
	return count, nil
}

// GetInviteeCount 获取邀请用户数
func (r *userRepositoryImpl) GetInviteeCount(address string) (int64, error) {
	var count int64
	result := r.db.Model(&models.User{}).Where("parent_id = ?", address).Count(&count)
	if result.Error != nil {
		logger.ErrorF("Failed to get invitee count: %v", result.Error)
		return 0, result.Error
	}
	return count, nil
} 